import React, { Component } from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';

import { actionCreators } from '../../otherReducer/user';

class AuthRouter extends Component {
    componentDidMount() {
        const publicUrl = ['/login', '/register'];
        const currentUrl = this.props.location.pathname;

        if (publicUrl.indexOf(currentUrl) > -1) {
            return null;
        }

        axios.get('/user/info').then((res) => {
            if (res.data.code === 0) {
                this.props.loginSuccess(res.data.data);
            } else {
                this.props.history.push('/login');
            }
        }).catch((error) => {   
            console.log(error);
        });
    }

    render() {
        return <p></p>
    }
}
const mapDispatchToProps = (dispatch) => ({
    loginSuccess(userMsg) {
        dispatch(actionCreators.loginSuccess(userMsg));
    }
})
export default connect(null, mapDispatchToProps)(withRouter(AuthRouter));